var WxParse = require('../../wxParse/wxParse.js');
//index.js
//获取应用实例
var app = getApp();
var speed = 100,k = 0;
const innerAudioContext = wx.createInnerAudioContext();
Page({
  data: {
    circleList: [],//圆点数组
    awardList: [],//奖品数组
    indexSelect: 0,//被选中的奖品index
    isRunning: false,//是否正在抽奖
    awardBtn:true,
    modelshow:false,
    textH:0,
    isShowmyaward:false
  },
  onLoad: function (e) {
    var that = this;
    if (e && e.scene) {
      var scene = decodeURIComponent(e.scene).split('&');
      console.log(scene);
      var secneObj = {};
      for (var i = 0; i < scene.length; i++) {
        var arr = scene[i].split('=');
        var key = arr[0];
        secneObj[key] = arr[1];
      }
      e = secneObj;
    }
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }

    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        that.getSlient();
      }
    } else {
      that.getSlient();
    }
  },
  onReady: function (e) {
    innerAudioContext.autoplay = false;
    innerAudioContext.src = 'http://tiandiantong.oss-cn-beijing.aliyuncs.com/questionMusic/lotterymusic.mp3';
  },
  onShow:function(){
    var that = this;
    that.setCircle();
    if (!app.globalData.plumSession) {
      app.wechatSq(that);
    } else {
      app.requestAd(that);
      that.award();
    }
  },
  initPage: function(){
    var that = this;
    that.onLoad();
    that.onShow();
  },
  getSlient:function(){
    var that = this;
    var slient = app.globalData.slient ? app.globalData.slient:'';
    that.setData({
      slient: slient
    })
    // if (slient == 1) {
    //   wx.hideTabBar()
    // }
  },
  setCircle:function(){
    var _this = this;
    //圆点设置
    var leftCircle = 20;
    var topCircle = 20;
    var circleList = [];
    for (var i = 0; i < 16; i++) {
      if (i == 0) {
        topCircle = 20;
        leftCircle = 20;
      } else if (i < 4) {
        topCircle = 12;
        leftCircle = leftCircle + 134;
      } else if (i == 4) {
        topCircle = 20;
        leftCircle = 548;
      } else if (i < 8) {
        topCircle = topCircle + 134;
        leftCircle = 552;
      } else if (i == 8) {
        topCircle = 544;
        leftCircle = 548;
      } else if (i < 12) {
        topCircle = 552;
        leftCircle = leftCircle - 134;
      } else if (i == 12) {
        topCircle = 544;
        leftCircle = 20;
      } else if (i < 16) {
        topCircle = topCircle - 134;
        leftCircle = 12;
      } else {
        return;
      }
      circleList.push({ topCircle: topCircle, leftCircle: leftCircle });
    }
    this.setData({
      circleList: circleList
    })
  },
  award:function(){
    var that= this;
    console.log(app.globalData.requestUrl);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_meeting_lottery',
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.ec == 200) {
          var awardCfg = res.data.data;
          awardCfg.startTime = parseInt(awardCfg.startTime);
          that.setData({
            // awardList: res.data.data.goodsList,
            imageAward: awardCfg.goodsList,
            awardCfg: awardCfg
          })
          console.log(awardCfg);
          that.countDjs();
          var article = awardCfg.rule;
          // 富文本解析
          WxParse.wxParse('article', 'html', article, that, 5);
          // console.log(that.data.imageAward)
          //奖品item设置
          var awardList = [];
          //间距
          var topAward = 12;
          var leftAward = 12;
          for (var j = 0; j < 8; j++) {
            if (j == 0) {
              topAward = 12;
              leftAward = 12;
            } else if (j < 3) {
              topAward = topAward;
              //150是宽.15是间距.下同
              leftAward = leftAward + 150 + 12;
            } else if (j < 5) {
              leftAward = leftAward;
              //150是高,15是间距,下同
              topAward = topAward + 150 + 12;
            } else if (j < 7) {
              leftAward = leftAward - 150 - 12;
              topAward = topAward;
            } else if (j < 8) {
              leftAward = leftAward;
              topAward = topAward - 150 - 12;
            }
            var imageAward = that.data.imageAward[j];
            awardList.push({ topAward: topAward, leftAward: leftAward, imageAward: imageAward });
          }
          that.setData({
            awardList: awardList
          })
          console.log(that.data.awardList);
        } else {
          console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  startGame: function () {
    var that = this;
    app.getSubId(that, 'applet_meeting_start_lottery', 'toStartGame');
  },
  //开始游戏
  toStartGame: function () {
    var that = this;
    if (app.globalData.slient == 1) {
      return;
    }
    if (!that.data.awardCfg) {
      return;
    }
    console.log(that.data.awardCfg)
    var mobile = that.data.awardCfg.mobile ? that.data.awardCfg.mobile : '';
    if(!mobile){
      that.setData({
        isShowgetmobile:true
      })
      return;
    }
    var remainTimes = that.data.awardCfg.restNum;
    if (remainTimes <= 0) {
      var myLottery = {
        status:false,
        msg:'很遗憾你没有抽奖次数了哦！'
      };
      that.setData({
        myLottery: myLottery,
        isShowmyaward: true,
        isRunning: false
      })
      return;
    }
    if (this.data.isRunning) return;
    this.setData({
      isRunning: true
    })
    var that = this;
    var indexSelect = 0
    var i = 0;
    console.log(indexSelect);
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_meeting_start_lottery',
        id: that.data.awardCfg.actId
      },
      success: function (res) {
        console.log(res);
        if (res.data.ec==200) {
          console.log(res.data.data);
          innerAudioContext.play();
          console.log(innerAudioContext)
          that.rewardActive(i, res, indexSelect, speed);
        } else if (res.data.ec==500){
          // console.log(res.data)
          app.errorTip(that, res.data.em, 2000);
          that.setData({
            isRunning: false
          })
        } else if (res.data.ec==600){
          that.rewardActive(i, res, indexSelect, speed);
        }else{
          app.errorTip(that, res.data.em, 2000);
          that.setData({
            isRunning: false
          })
        }

      },
      complete: function () {
        // wx.hideToast();
        wx.stopPullDownRefresh();
      }
    });
  },
  rewardActive: function (i, res, indexSelect,speedNew){
    var that = this;
    // console.log(i);
    // console.log(res);
    // console.log(indexSelect);
    var timer = setTimeout(function () {
      indexSelect++;
      
      //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度
      i += 20;
      if (i>500){
        speed = parseInt(speed) + parseInt(30);
      }
      if(i==660){
        var curSpeed = speed;
        var curIndex = parseInt(indexSelect);
        var end = parseInt(res.data.data.index);
        var m = '';
        if(end>curIndex){
          m = end - curIndex;
        }else{
          m = 8 - curIndex + end;
        }
        k = 660 + m * 20;
      }
      if (k>0 && i > k) {
        // var indexSelect = res.data.award.id + 1
        // var indexSelect = '';
        var awardCfg = that.data.awardCfg;
        awardCfg.joinNum++;
        var myLottery = {
          name: res.data.data.name,
          img: res.data.data.img,
        }
        awardCfg.restNum = res.data.data.restNum;
        awardCfg.myLottery = myLottery;
        console.log("当前奖品数据");
        console.log(indexSelect);
        console.log(myLottery);
        that.setData({
          awardCfg: awardCfg,
          myLottery: res.data.data,
          indexSelect: res.data.data.index,
          awardTitle: res.data.data.msg,
          isShowmyaward: true,
          isRunning: false
        })
        console.log(innerAudioContext)
        innerAudioContext.stop();
        clearInterval(timer);
        speed = 100;
        return;
      }
      indexSelect = indexSelect % 8;
      that.setData({
        indexSelect: indexSelect
      })
      that.rewardActive(i, res, indexSelect, speed)
    }, speedNew)
    
  },
  onPullDownRefresh: function () {
    var that = this;
    that.onShow();
    console.log("下拉刷新");
  },
  getPhoneNumber: function (e) {
    var that = this;
    console.log(e);
    wx.login({
      success: function (res) {
        if (res.code) {
          var data = {
            map: 'applet_bind_member_mobile',
            code: res.code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          };
          that.requestMobile(data);
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  requestMobile: function (data) {
    console.log(data);
    var that = this;
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    console.log(app.globalData.requestUrl);
    console.log(data);
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var mobile = res.data.data;
          var awardCfg = that.data.awardCfg;
          awardCfg.mobile = mobile;
          that.setData({
            awardCfg: awardCfg
          })
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  mobileChange:function(e){
    this.setData({
      mobile:e.detail.value
    })
  },
  hidegetmobile:function(){
    this.setData({
      isShowgetmobile: false
    })
  },
  requestMobilenew: function () {
    var that = this;
    var data = {
      map: 'applet_update_member_info',
      mobile: that.data.mobile
    };
    // var isMob = /^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/;
    // var isPhone = /^(0[0-9]{2,3})([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/;
    // if (!isMob.test(data.mobile)) {
    //   app.errorTip(that, "请输入正确的手机号", 2000);
    //   return;
    // }
    if (!data.mobile){
      app.errorTip(this, "请输入正确的手机号", 2000);
      return;
    }
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var awardCfg = that.data.awardCfg;
          awardCfg.mobile = data.mobile;
          that.setData({
            awardCfg: awardCfg,
            isShowgetmobile:false
          })
          app.errorTip(that, "提交成功！", 2000);
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  showAward:function(){
    var awardCfg = this.data.awardCfg.myLottery;
    if (!awardCfg){
      app.errorTip(this, '暂未参加任何抽奖', 2000);
      return;
    }
    this.setData({
      awardTitle: "我的奖品",
      isShowmyaward: true
    })
  },
  hideAward: function () {
    this.setData({
      isShowmyaward: false
    })
  },
  modelshow:function(){
    var that =this;
    var modelshow=!that.data.modelshow;
    that.setData({
      modelshow: modelshow
    })
  },
  modelhidden:function(){
    var that = this;
    var modelshow = !that.data.modelshow;
    that.setData({
      modelshow: modelshow
    })
  },
  rewardChange:function(e){
    var that = this;
    var actid = e.currentTarget.dataset.actid;
    var pointsCost= e.currentTarget.dataset.pointscost;
    var totalPoints = e.currentTarget.dataset.totalpoints;
    wx.navigateTo({
      url: '/subpages/rewardChange/rewardChange?actid='+actid+'&totalPoints=' + totalPoints + '&pointsCost=' + pointsCost,
    })
  },
  toRewardrecords:function(){
    var award = this.data.awardCfg;
    if (award){
      if (award.actId){
        var id = award.actId;
        wx.navigateTo({
          url: '/subpages/rewardRecords/rewardRecords?id=' + id,
        })
      }
    }
  },
  countDjs: function () {
    var that = this;
    var awardCfg = that.data.awardCfg;
    var startTime = awardCfg.startTime;
    var curtime = parseInt((new Date()).getTime()/1000);
    var remainTime = startTime - curtime;
    if (remainTime>0){
      clearInterval(that.data.intervarID);
      that.data.intervarID = setInterval(function () {
        remainTime--;
        awardCfg.remainTime = remainTime;
        that.setData({
          awardCfg: awardCfg
        })
        that.djs(remainTime);
      }, 1000)
    }else{
      awardCfg.remainTime = 0;
      that.setData({
        awardCfg: awardCfg
      })
      clearInterval(that.data.intervarID);
    }
  },
  djs: function (time) {
    var that = this;
    var leftTime = time;
    that.setData({
      leftTime: leftTime
    })
    if (leftTime > 0) {
      var days = parseInt(leftTime / 60 / 60 / 24, 10);
      var hours = parseInt(leftTime / 60 / 60 % 24, 10);
      var minutes = parseInt(leftTime / 60 % 60, 10);
      var seconds = parseInt(leftTime % 60, 10);
      days = days < 10 ? '0' + days : days;
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      that.setData({
        days: days,
        hours: hours,
        minutes: minutes,
        seconds: seconds
      })
      if (days == '00' && hours == '00' && minutes == '00' && seconds == '00') {
        clearInterval(that.data.intervarID);
      }
    } else {
      that.setData({
        days: '00',
        hours: '00',
        minutes: '00',
        seconds: '00',
      })
    }
  },
  hideGetuser: function () {
    var that = this;
    that.setData({
      isShowgetuser: false
    })
  },
  // 获取用户信息
  getuserInfo: function (e) {
    var that = this;
    if (e.detail.userInfo) {
      var userdata = e.detail;
      console.log(userdata);
      var slient = that.data.slient;
      var again = false;
      if (slient == 0) {
        again = true;
      }
      app.getuserInfo(that, userdata, again);
    }
  },
  onShareAppMessage: function () {
    var that = this;
    console.log("分享");
    var award = that.data.awardCfg;
    if (award) {
      if (award.actId) {
        var id = award.actId;
        setTimeout(function(){
          wx.request({
            url: app.globalData.requestUrl,
            data: {
              map: 'applet_meeting_share_lottery',
              id: id
            },
            success: function (res) {
              console.log(res.data)
              if (res.data.ec == 200) {
                var awardCfg = that.data.awardCfg;
                awardCfg.restNum = res.data.data.num;
                that.setData({
                  awardCfg: awardCfg
                })
                app.errorTip(that, '分享成功', 2000);
              } else {
                app.errorTip(that, res.data.em, 2000);
              }
            }
          });
        },3000)
      }
    }
    app.getPoint(that);
    return {
      path: '/subpages/getReward/getReward'
    }
  },
})

